package com.glory.hikvisionmobile.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.hikvisionmobile.R;
import com.glory.hikvisionmobile.adapter.DataCollectListAdapter;
import com.glory.hikvisionmobile.base.BaseActivity;
import com.glory.hikvisionmobile.base.Constant;
import com.glory.hikvisionmobile.bean.DataCollect.DataCollectBean;
import com.glory.hikvisionmobile.bean.DataCollect.GeneralSetLoadBean;
import com.glory.hikvisionmobile.bean.DataCollect.XEdcItemSetBean;
import com.glory.hikvisionmobile.bean.DataCollect.XEdcItemSetLinesBean;
import com.glory.hikvisionmobile.bean.net.BaseResponseBean;
import com.glory.hikvisionmobile.utils.DialogUtils;
import com.glory.hikvisionmobile.utils.EditTextEnterUtils;
import com.glory.hikvisionmobile.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.entity.FreeUI_AddViewEntity;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ActivityManager;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_EditTextUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StringUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class Work_DataCollectActivity extends BaseActivity implements BaseQuickAdapter.OnItemClickListener {


    @BindView(R.id.etEqpWorkNum)
    FreeUI_ClearEditText etEqpWorkNum;
    @BindView(R.id.tvParamListCode)
    TextView tvParamListCode;
    @BindView(R.id.ivParamListArrow)
    ImageView ivParamListArrow;
    @BindView(R.id.flParamList)
    FrameLayout flParamList;
    @BindView(R.id.etPieceNum)
    FreeUI_ClearEditText etPieceNum;
    @BindView(R.id.tvSearch)
    TextView tvSearch;
    @BindView(R.id.rvDataCollectInfoList)
    RecyclerView rvDataCollectInfoList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.tvReplay)
    TextView tvReplay;

    private FreeUI_GeneralPop codePop;
    private DataCollectListAdapter dataCollectListAdapter;
    private String paramCode;
    private List<XEdcItemSetLinesBean> xEdcItemSetLinesBeans;
    private List<String> edcItemName;
    private String eqpWork;
    private String paramList = "";
    private String keepNum;


    @Override
    protected int getLayoutResId() {
        return R.layout.activity_data_collect1;
    }

    @Override
    protected void initView() {
        Bundle bundle = getIntent().getExtras();
        eqpWork = bundle.getString("eqpWork");
        paramList = bundle.getString("paramList");
        keepNum = bundle.getString("position");
        etEqpWorkNum.setText(eqpWork);
        tvParamListCode.setText(paramList);
        if (FreeApi_StringUtils.isEmpty(eqpWork)){
            initEdit(etEqpWorkNum, s -> requestParams(s));
        }else {
            etEqpWorkNum.setFocusable(false);
            queryDataList(paramList);
        }
        rvDataCollectInfoList.setLayoutManager(new LinearLayoutManager(Work_DataCollectActivity.this));
        rvDataCollectInfoList.setItemAnimator(new DefaultItemAnimator());
        rvDataCollectInfoList.addItemDecoration(new DividerItemDecoration(Work_DataCollectActivity.this, 1));
        dataCollectListAdapter = new DataCollectListAdapter(null);
        dataCollectListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        dataCollectListAdapter.isFirstOnly(true);
        rvDataCollectInfoList.setAdapter(dataCollectListAdapter);

        dataCollectListAdapter.setOnItemClickListener(this);
        edcItemName = new ArrayList<>();
    }

    private void requestParams(String equipmentId) {
        JsonObject map = new JsonObject();
        map.addProperty("equipmentId",equipmentId);
        NetUtils.requestDara("HIK.PdaGeneralSetLoad",this,map,new FreeUI_DialogEntityCallBack<BaseResponseBean<GeneralSetLoadBean>>
                (new TypeToken<BaseResponseBean<GeneralSetLoadBean>>(){}.getType(),getSupportFragmentManager(),this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<GeneralSetLoadBean>> response) {
                super.onSuccess(response);
                edcItemName.clear();
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    List<XEdcItemSetBean> xEdcItemSetBeans = response.body().getBody().getxEdcItemSets();
                    for (XEdcItemSetBean bean : xEdcItemSetBeans){
                        edcItemName.add(bean.getEdcItemName());
                    }
                    if (codePop == null) {
                        codePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flParamList.getWidth(), edcItemName, ivParamListArrow, (code, i) -> {
                            tvParamListCode.setText(code);
                            paramCode = code;
                        });

                    }
                }

            }

            @Override
            public void onError(Response<BaseResponseBean<GeneralSetLoadBean>> response) {
                super.onError(response);
                loadError(response.getException(),"HIK.PdaGeneralSetLoad");


            }
        });
    }


    @Override
    protected void initData() {

    }

    @Override
    protected FreeUI_AddViewEntity getBaseEntity() {
        freeUI_titleView.setTitle("数据采集");
        freeUI_titleView.setRightListener(R.drawable.selector_refresh, v -> {
            queryDataList(FreeApi_StringUtils.isEmpty(paramList) ? paramCode : paramList);
        });
        return new FreeUI_AddViewEntity("header", llMain);
    }


    @OnClick({R.id.flParamList, R.id.tvSearch,R.id.tvReplay})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.flParamList:
                if (!FreeApi_StringUtils.isEmpty(paramList)){
                    return;
                }
                if (codePop == null) {
                    showToast("未请求到参数集列表，请重新扫描设备号", false);
                    etEqpWorkNum.setText("");
                    etEqpWorkNum.requestFocus();
                    return;
                }
                if (codePop.isShowing()) {
                    codePop.dismiss();
                } else {
                    FreeApi_PopUtils.setArrowShow(ivParamListArrow);
                    codePop.showAsDropDown(flParamList, 0, 0);
                }
                break;
            case R.id.tvSearch:
                if (actionControl("Search","PDAWorkFragment"))
                    return;

                queryDataList(FreeApi_StringUtils.isEmpty(paramList) ? paramCode : paramList);
                break;
            case R.id.tvReplay:
                if (actionControl("Submit","PDAWorkFragment"))
                    return;

                submitData();
                break;
        }
    }

    private void submitData() {


        DialogUtils.showLoginDialog(this, Constant.CURRENT_USER, new DialogUtils.signCallback() {
            @Override
            public void onSignSuccess() {

                JsonObject map = new JsonObject();
                map.addProperty("edcSetId",FreeApi_StringUtils.isEmpty(paramList) ? paramCode : paramList);
                map.addProperty("mainEquipmentId",etEqpWorkNum.getText().toString().trim());
                JsonArray jsonArray = new JsonArray();

                for (XEdcItemSetLinesBean xEdcItemSetLinesBean : xEdcItemSetLinesBeans) {
                    JsonObject js = new JsonObject();
                    JsonObject js1 = new JsonObject();
                    js1.add("XPdaDcModel",new JsonParser().parse(new Gson().toJson(xEdcItemSetLinesBean.getXPdaDcModels())).getAsJsonArray());
                    js.add("XPdaDcModels",js1);
                    JsonObject js2 = new JsonObject();
                    js2.add("XPdaComponent",new JsonParser().parse(new Gson().toJson(xEdcItemSetLinesBean.getxPdaComponents())).getAsJsonArray());
                    js.add("xPdaComponents",js2);
                    js.addProperty("edcItemLineName",xEdcItemSetLinesBean.getEdcItemLineName());
                    js.addProperty("dataType",xEdcItemSetLinesBean.getDataType());
                    js.addProperty("edcSampleType",xEdcItemSetLinesBean.getEdcSampleType());
                    jsonArray.add(js);
                }
                JsonObject js3 = new JsonObject();
                js3.add("XPdaEdcData",new JsonParser().parse(new Gson().toJson(jsonArray)));
                map.add("xPdaEdcDatas",js3);
                NetUtils.requestDara("HIK.PdaGeneralSubmit", this, map,  new FreeUI_DialogEntityCallBack<BaseResponseBean<?>>
                        (new TypeToken<BaseResponseBean<?>>(){}.getType(),getSupportFragmentManager(),this) {

                    @Override
                    public void onSuccess(Response<BaseResponseBean<?>> response) {
                        super.onSuccess(response);
                        if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                            if (FreeApi_StringUtils.isEmpty(paramList)){
                                showConfirmDialog(Work_DataCollectActivity.this,"提交成功");
                            }else {
                                Intent intent = new Intent();
                                intent.putExtra("position",keepNum);
                                setResult(Activity.RESULT_OK, intent);
                                FreeApi_ActivityManager.getActivityManager().finishActivity();
                            }

                        }
                    }

                    @Override
                    public void onError(Response<BaseResponseBean<?>> response) {
                        super.onError(response);
                        loadError(response.getException(),"HIK.PdaGeneralSubmit");
                    }
                });

            }
        },getSupportFragmentManager());

    }


    private void queryDataList(String paramCode) {
        if (!editIsEmpty(etEqpWorkNum, "请扫描设备号")) {
            return;
        }
        if (FreeApi_StringUtils.isEmpty(paramCode)) {
            showToast("请选择参数集", false);
            return;
        }

        JsonObject map = new JsonObject();
        map.addProperty("edcSetId", paramCode);
        map.addProperty("mainEquipmentId",etEqpWorkNum.getText().toString().trim());
        NetUtils.requestDara("HIK.PdaGeneralLoad", this, map, new FreeUI_DialogEntityCallBack<BaseResponseBean<DataCollectBean>>
                (new TypeToken<BaseResponseBean<DataCollectBean>>(){}.getType(),getSupportFragmentManager(),this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<DataCollectBean>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    xEdcItemSetLinesBeans = response.body().getBody().getxEdcItemSetLines();
                    dataCollectListAdapter.setNewData(xEdcItemSetLinesBeans);
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<DataCollectBean>> response) {
                super.onError(response);
                loadError(response.getException(),"HIK.PdaGeneralLoad");
            }
        });
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
            Intent intent = new Intent(this,DataCollectDetailsActivity.class);
            intent.putExtra("postion",position);
            intent.putParcelableArrayListExtra("xEdcItemSetLinesBeans", (ArrayList<? extends Parcelable>) xEdcItemSetLinesBeans);
            startActivityForResult(intent,200);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK){
            if (requestCode == 200){
                if (data != null){
                    xEdcItemSetLinesBeans = data.getParcelableArrayListExtra("xEdcItemSetLinesBeans");
                }
            }
        }

    }
}
